<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 5/25/21
 * Time: 8:55 PM
 */

namespace app\api\controller\v1;


use app\api\model\Team as TeamModel;
use LinCmsTp5\exception\ParameterException;
use app\api\model\TeamUser as TeamUserModel;

// 团信息
class Team extends Base
{
    /**
     * 获取团列表
     */
    public function getDataAll()
    {
        return TeamModel::order('id desc')->select()->toArray();
    }


    /**
     * 获取团列表
     * @validate('PagingParameter')
     */
    public function getDataList($name,$page,$limit)
    {
        $where = [];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        $query = TeamModel::where($where)->with('product')->order('id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->each(function ($item){
            $item['team_url'] = config('setting.qr_prefix').'team_'.$item['id'].'.png';
        })->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取团详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return TeamModel::get($id);
    }

    /**
     * 添加店面信息
     * @validate('CheckTeam')
     */
    public function createData($name,$product_id,$remarks,$desc)
    {
        $mode = TeamModel::create([
            'name' => $name,
            'product_id' => $product_id,
            'remarks' => $remarks,
            'desc' => $desc
        ]);
        $data['scene'] = 'team-' . $mode->id;
        $data['page'] = 'pages/invite/team';
        $data['width'] = 280;
        $code_name = 'team_' . $mode->id;
        $this->setCodePub($data,$code_name);
        return writeJson(201, [], '添加成功！');
    }

    /**
     * 修改团信息
     * @validate('CheckTeam')
     */
    public function updateData($id,$name,$product_id,$remarks,$desc)
    {
        $info = TeamModel::get($id);
        if($info) {
            $info->name = $name;
            $info->product_id = $product_id;
            $info->remarks = $remarks;
            $info->desc = $desc;
            $info->save();
            $data['scene'] = 'team-' . $id;
            $data['page'] = 'pages/invite/team';
            $data['width'] = 280;
            $code_name = 'team_' . $id;
            $this->setCodePub($data,$code_name);
        }
        return writeJson(202, [], '修改成功！');
    }

    /**
     * 删除团信息
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        // 关联团长
        $teamOwner = TeamUserModel::where('team_id',$id)->select();
        if(!$teamOwner->isEmpty()) {
            throw new ParameterException([
                'msg' => [
                    'team' => '团下还有关联人员,不能删除团！'
                ]
            ]);
        }
        TeamModel::destroy($id);
        return writeJson(202, [], '删除成功！');
    }
}